#include"apue.h"
#include"ftp.h"
void cli_login(int sockfd,char *ser_ip)
{
	struct ser_to_cli login_res;
	struct sockaddr_in addr;
	struct cli_to_ser buf;
	int addrlen=sizeof(struct sockaddr_in);
	char *passwd;
	
	bzero(&addr,sizeof(addr));
	addr.sin_family=AF_INET;
	addr.sin_port=htons(DEFAULT_PORT);
	addr.sin_addr.s_addr=inet_addr(ser_ip);

	bzero(&buf,sizeof(buf));
	printf("name:");
	gets(buf.ftp_arg.arglogin.login_user);
	passwd=getpass("passwd:");
	strcpy(buf.ftp_arg.arglogin.login_passwd,passwd);
	sendto(sockfd,&buf,sizeof(buf),0,(struct sockaddr *)&addr,sizeof(addr));
	bzero(&login_res, sizeof(login_res));
	bzero(&addr,sizeof(addr));

	recvfrom(sockfd,&login_res,sizeof(login_res),0,(struct sockaddr*)&addr,&addrlen);
	if(login_res.result== SUCCESS)
	{
		printf("login successfull!\n");
	}else
	{
		printf("login failed! %s\n",login_res.string_result);
		close(sockfd);
		exit(0);
	}
	//return NULL;

}
int main(int argc,char *argv[])
{	
	int sockfd;
	int ret;
	struct sockaddr_in addr;
	struct sockaddr_in ser_addr;
	char cmd[50];
	int cmd_stat=CMD_LOGIN;
	struct cli_to_ser cmd_struct;

	if(argc!=2)
	{
		fprintf(stderr,"缺少服务器地址:%s\n",argv[0]);
		return 1;
	}
	//创建网络链接udp
	sockfd=socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd<0)
	{
		perror("sockfd");
		return 1;
	}
	bzero(&addr,sizeof(addr));
	addr.sin_family=AF_INET;
	addr.sin_port=htons(9515);
	addr.sin_addr.s_addr=htonl(INADDR_ANY);
	ret=bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
	if(ret<0)
	{
		perror("bind");
		goto ERR;
	}
	bzero(&ser_addr,sizeof(ser_addr));
	ser_addr.sin_family=AF_INET;
	ser_addr.sin_port=htons(DEFAULT_PORT);
	ser_addr.sin_addr.s_addr=inet_addr(argv[1]);
	//获取要发送的命令
	while(1)
	{
		switch(cmd_stat)
		{
			case CMD_LOGIN:
				{
					cli_login(sockfd, argv[1]);
					cmd_stat=CMD_EMPTY;
					break;
				}
			case CMD_CD:
				cli_cd(sockfd,&ser_addr,&cmd_struct);
				cmd_stat=CMD_EMPTY;
				break;
			case CMD_PWD:
 				cli_pwd(sockfd,&ser_addr,&cmd_struct);
				cmd_stat=CMD_EMPTY;
				break;
			case CMD_LS:
				cli_ls(sockfd,&ser_addr,&cmd_struct);
				cmd_stat=CMD_EMPTY;
				break;
			case CMD_GET:
				cli_get(sockfd,&ser_addr,&cmd_struct);
				cmd_stat=CMD_EMPTY;
				break;
			case CMD_PUT:
				cli_put(sockfd,&ser_addr,&cmd_struct);
				cmd_stat=CMD_EMPTY;
				break;
			case CMD_QUIT:
				ret=cli_quit(sockfd,&ser_addr,&cmd_struct);
				if(ret==SUCCESS)
				{exit(0);}else
				{	
					printf("quit fail\n");
					cmd_stat=CMD_EMPTY;
					break;
				}
			case CMD_EMPTY:
				{
					printf(FTP_INFO);
					fflush(stdout);
					bzero(cmd,sizeof(cmd));
					gets(cmd);
					cmd_struct.ftm_cmd=CMD_EMPTY;
					bzero(&cmd_struct.ftp_arg.arg,sizeof(cmd_struct.ftp_arg.arg));
					//判断命令 分割命令和参数
					judge_cmd(cmd,&cmd_struct);
					printf("命令=%d,参数=%s\n",cmd_struct.ftm_cmd,
							cmd_struct.ftp_arg.arg);
					cmd_stat=cmd_struct.ftm_cmd;
					break;
				}
			default:printf("cmd is error.\n");
					cmd_stat=CMD_EMPTY;
					break;
		}
	}
ERR:
	close(sockfd);
	return 0;
}
